package com.ub.party.web.base;

import com.ub.party.web.constants.ShreecConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * Created by Hanran on 2016/8/27.
 */
@Component
public class CookieHelper {

    private static final String code = "UTF-8";

    public String getCookieValue(HttpServletRequest request, String name) {
        if (request == null || name == null || name.length() == 0) {
            return null;
        }
        Cookie cookies[] = request.getCookies();
        if (cookies == null) {
            return null;
        }

        try {
            String newName = URLEncoder.encode(name, code);
            for (Cookie cookie : cookies) {
                if (newName.equalsIgnoreCase(cookie.getName())) {
                    return URLDecoder.decode(cookie.getValue(), code);
                }
            }
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e.getMessage());
        }
        return null;
    }
    // 设置cookie
    public void setCookie(HttpServletResponse response, String name, String value) {
        if (response != null) {
            Cookie cookie = new Cookie(name, value);
            cookie.setMaxAge(getDefaultCookieAge());
            response.addCookie(cookie);
        }
    }

    public int getDefaultCookieAge() {
        return ShreecConstants.EXPIRED_TIME_SECOND;
    }
}
